package com.sali.disruptor;

import com.lmax.disruptor.WorkHandler;
import com.lmax.disruptor.dsl.ProducerType;
import com.sali.disruptor.enums.WaitStrategyEnum;
import com.sali.disruptor.exceptions.DisruptorExceptionHandler;

import java.util.List;
import java.util.concurrent.ThreadFactory;

/**
 * @description:
 * @author: sali
 * @date: 2025/2/22 下午2:55.
 * @version: 1.0
 */
public abstract class BaseDisruptor {

    private int waitStrategy;

    private int ringBufferSize;

    private ThreadFactory threadFactory;

    private MessageProducer messageProducer;

    private DisruptorComponent disruptorComponent;

    public BaseDisruptor(int waitStrategy, int ringBufferSize, ThreadFactory threadFactory) {
        this.waitStrategy = waitStrategy;
        this.ringBufferSize = ringBufferSize;
        this.threadFactory = threadFactory;
    }


    /**
     * 获取自定义消费者
     */
    public abstract List<WorkHandler> getConsumer();

    public void start() {
        List<WorkHandler> workHandlers = getConsumer();
        WaitStrategyEnum strategyEnum = WaitStrategyEnum.valueOf(waitStrategy);
        // disruptor对象生成
        disruptorComponent = DisruptorComponent.createBuilder().ringBufferSize(ringBufferSize).waitStrategyEnum(strategyEnum).workHandlers(workHandlers).producerType(ProducerType.MULTI).exceptionHandler(new DisruptorExceptionHandler()).threadFactory(threadFactory).build();
        disruptorComponent.start();
        // disruptor消息存放对象生成
        messageProducer = MessageProducer.createBuilder().disruptorComponent(disruptorComponent).build();
    }

    public MessageProducer getMessageProduction() {
        return messageProducer;
    }

    public DisruptorComponent getDisruptorComponent() {
        return disruptorComponent;
    }

}
